import { useCallback, useEffect, useMemo, useState } from 'react';
import { getPageMeta } from '@/services/request/meta';
import { initialSchema } from '@/components/schema-form-render/utils';
import _ from 'lodash';
import { MetaTableItem } from './interface';
import { triggerTableCellRender } from './triggerPlugin';
import { TableColumnProps } from 'antd';

import { ISchema } from '@formily/react';

interface PageMetaConfigData {
  initLoading: boolean;
  jsonSchema: ISchema;
  columns: TableColumnProps<any>[];
}

export const useGetPageMeta = (formCode?: string): PageMetaConfigData => {
  const [columns, setColumns] = useState<TableColumnProps<any>[]>([]);
  const [jsonSchema, setJsonSchema] = useState({});
  const [loading, setLoading] = useState<boolean>(false);
  useEffect(() => {
    if (formCode) {
      setLoading(true);
      getPageMeta(formCode)
        .then((res: any) => {
          const { result } = res;
          const { tableColumns, schema } = initialSchema(_.cloneDeep(result), 'SEARCH') as any;
          setJsonSchema(schema);
          setColumns(
            tableColumns?.map((item: any) => {
              const { label, key, columnRenderType } = item as MetaTableItem;
              const dataIndex = key;
              return {
                dataIndex,
                title: label,
                ellipsis: true,
                render: (text: string, record: any, index: number) =>
                  columnRenderType
                    ? triggerTableCellRender(columnRenderType, {
                        ...record,
                        rowIndex: index,
                      })
                    : text,
              };
            }),
          );
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [formCode]);

  return {
    initLoading: loading,
    jsonSchema,
    columns,
  };
};

type VisibleModalType = [boolean, () => true, () => false];

export const useVisible = (defaultVisible?: boolean): VisibleModalType => {
  const [visible, setVisible] = useState<boolean>(defaultVisible || false);

  const hiddenModal = useCallback((): false => {
    setVisible(false);
    return false;
  }, []);

  const showModal = useCallback((): true => {
    setVisible(true);
    return true;
  }, []);

  return [visible, showModal, hiddenModal];
};

interface PaginationConfig {
  current?: number;
  total?: number;
  pageSize?: number;
}

export enum PaginationKey {
  CURRENT = 'CURRENT',
  PAGE_SIZE = 'PAGE_SIZE',
  TOTAL = 'TOTAL',
}

export const usePagination = (
  defaultConfig: PaginationConfig,
): [Required<PaginationConfig>, (key: PaginationKey, val: number) => void] => {
  const [current, setCurrent] = useState<number>(defaultConfig.current || 1);

  const [pageSize, setPageSize] = useState<number>(defaultConfig.pageSize || 10);
  const [total, setTotal] = useState<number>(defaultConfig.total || 0);

  const pagination = useMemo(() => {
    return {
      current,
      pageSize,
      total,
    };
  }, [current, pageSize, total]);

  const updatePagination = useCallback((key: PaginationKey, val: number) => {
    switch (key) {
      case PaginationKey.CURRENT: {
        setCurrent(val);
        break;
      }
      case PaginationKey.PAGE_SIZE: {
        setPageSize(val);
        break;
      }
      case PaginationKey.TOTAL: {
        setTotal(val);
        break;
      }
      default: {
        console.warn(key, val);
        break;
      }
    }
  }, []);

  return [pagination, updatePagination];
};

export const useRefresh = (): [boolean, () => void] => {
  const [refresh, setRefresh] = useState(false);

  const updateRefresh = useCallback(() => {
    setRefresh((val) => !val);
  }, []);

  return [refresh, updateRefresh];
};
